package com.cdream.basic.algorithm.leetcode.findElement;

import java.util.HashMap;
import java.util.Map;

/**
 * @author cdream
 * @date 7/8/21
 */
public class Question930 {
    public int numSubarraysWithSum(int[] nums, int goal) {
        int[] sums = new int[nums.length];
        sums[0] = nums[0];
        for(int i = 1;i<nums.length;i++){
            sums[i] = nums[i]+sums[i-1];
        }
        Map<Integer,Integer> map = new HashMap<>();
        map.put(0,1);
        int res = 0;
        for(int i = 0; i<sums.length;i++){
            Integer k = map.getOrDefault(sums[i]-goal,0);
            res +=k;
            map.put(sums[i],map.getOrDefault(sums[i],0)+1);
        }
        return res;
    }

    public static void main(String[] args) {
        new Question930().numSubarraysWithSum(new int[]{1,0,1,0,1},2);
    }
}
